package com.nomi.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nomi.blog.entity.Article;
import com.nomi.blog.entity.DTO.ArticleSearchDTO;
import com.nomi.blog.mapper.ArticleMapper;
import com.nomi.blog.service.ArticleService;
import com.nomi.blog.service.UserInfoService;
import com.nomi.blog.utils.Result;
import com.nomi.blog.utils.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ArticleServiceImpl implements ArticleService {
    // 创建日志记录器
    private static final Logger log = LoggerFactory.getLogger(ArticleServiceImpl.class);
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private UserInfoService userInfoService;

    // 获取默认封面图片
    private byte[] getDefaultCoverImage() {
        try {
            ClassPathResource resource = new ClassPathResource("images/article_cover.jpeg");
            Path path = Paths.get(resource.getURI());
            return Files.readAllBytes(path);
        } catch (IOException e) {
            log.error("Failed to read default cover image", e);
            return null;
        }
    }

    /**
     * 创建文章
     * @param article
     * @return
     */
    @Override
    @Transactional
    public Result createArticle(Article article) {
        article.setStatus("草稿");
        article.setPublishTime(null);
        article.setViewCount(0);

        System.out.println("getCoverImage"+ Arrays.toString(article.getCoverImage()));

        if(article.getCoverImage() == null){
            article.setCoverImage(getDefaultCoverImage());
        }

        int result = articleMapper.insert(article);
        if (result > 0) {
            return Result.success("文章创建成功", article);
        } else {
            return Result.fail("文章创建失败");
        }
    }

    /**
     * 更新文章
     * @param article
     * @return
     */
    @Override
    @Transactional
    public Result updateArticle(Article article) {
        if(article.getCoverImage() == null){
            article.setCoverImage(getDefaultCoverImage());
        }

        int result = articleMapper.updateById(article);
        if (result > 0) {
            return Result.success("文章更新成功", article);
        } else {
            return Result.fail("文章更新失败");
        }
    }

    /**
     * 发布文章
     * @param articleId
     * @return
     */
    @Override
    @Transactional
    public Result publishArticle(Long articleId) {
        // 获取当前用户ID（从 UserContext）
        Long currentUserId = UserContext.getCurrentUserId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        Article article = articleMapper.selectById(articleId);
        if (article == null){
            return Result.fail("文章不存在");
        }

        if(article.getCoverImage() == null){
            article.setCoverImage(getDefaultCoverImage());
        }

        article.setStatus("待审核");
        article.setPublishTime(new Date());

        // 根据发布时间生成时间归档
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        article.setArchiveType(sdf.format(article.getPublishTime()));

        int result = articleMapper.updateById(article);
        if (result > 0) {
            //文章发布成功，更新用户的文章数量
            Result updateResult = userInfoService.updateUserArticleCount(article.getUserId(),1);
            if(updateResult.getCode() == 200){
                return Result.success("文章发布成功,用户文章数量更新成功");
            }else{
                return Result.fail("文章发布成功，但用户文章数量更新失败");
            }
        }else{
            return Result.fail("文章发布失败");
        }
    }

    /**
     * 保存草稿
     * @param article
     * @return
     */
    @Override
    @Transactional
    public Result saveDraft(Article article) {
        // 获取当前用户ID（从 UserContext）
        Long currentUserId = UserContext.getCurrentUserId();
        if (currentUserId == null) {
            return Result.fail("用户未登录");
        }

        // 设置作者ID
        article.setUserId(currentUserId);

        if(article.getCoverImage() == null){
            article.setCoverImage(getDefaultCoverImage());
        }

        article.setStatus("草稿");
        article.setPublishTime(null);
        if(article.getId() == null){
            int result = articleMapper.insert(article);

            if(result > 0){
                return Result.success("草稿保存成功",  article);
            }else{
                return Result.fail("草稿保存失败");
            }
        }else{
            int result = articleMapper.updateById(article);
            if(result > 0){
                return Result.success("草稿保存成功",  article);
            }else{
                return Result.fail("草稿保存失败");
            }
        }
    }

    /**
     * 构建查询条件
     * @param searchDTO
     * @return
     */
    private QueryWrapper<Article> buildQueryWrapper(ArticleSearchDTO searchDTO){
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();

        // 文章标题模糊查询
        if (searchDTO.getTitle() != null && !searchDTO.getTitle().isEmpty()) {
            queryWrapper.like("title", searchDTO.getTitle());
        }

        // 用户昵称模糊查询，需要关联用户表
        if (searchDTO.getNickname() != null && !searchDTO.getNickname().isEmpty()) {
            queryWrapper.inSql("user_id", "SELECT id FROM user WHERE nickname LIKE '%" + searchDTO.getNickname() + "%'");
        }

        // 文章标签精确查询
        if (searchDTO.getTag() != null && !searchDTO.getTag().isEmpty()) {
            queryWrapper.eq("tag", searchDTO.getTag());
        }

        // 文章时间归档精确查询
        if (searchDTO.getArchiveType() != null && !searchDTO.getArchiveType().isEmpty()) {
            queryWrapper.eq("archive_type", searchDTO.getArchiveType());
        }

        // 排序设置
        if (searchDTO.getSortField() != null && !searchDTO.getSortField().isEmpty()) {
            if ("ASC".equals(searchDTO.getSortOrder())) {
                queryWrapper.orderByAsc(searchDTO.getSortField());
            } else {
                queryWrapper.orderByDesc(searchDTO.getSortField());
            }
        }

        return queryWrapper;
    }

    /**
     * 文章搜索
     * @param searchDTO
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result searchArticles(ArticleSearchDTO searchDTO, Integer pageNum, Integer pageSize) {
        QueryWrapper<Article> queryWrapper = buildQueryWrapper(searchDTO);
        Page<Article> page = new Page<>(pageNum, pageSize);
        IPage<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        return Result.success("文章搜索成功", articlePage);
    }

    /**
     * 搜索文章（不带分页）
     * @param searchDTO
     * @return
     */
    @Override
    public Result searchArticlesWithoutPage(ArticleSearchDTO searchDTO) {
        QueryWrapper<Article> queryWrapper = buildQueryWrapper(searchDTO);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success("文章搜索成功",  articles);
    }

    /**
     * 审核文章
     * @param articleId
     * @param status
     * @return
     */
    @Override
    @Transactional
    public Result reviewArticle(Long articleId, String status) {
        Article article = articleMapper.selectById(articleId);
        if (article == null){
            return Result.fail("文章不存在");
        }
        article.setStatus(status);
        int result = articleMapper.updateById(article);
        if (result > 0){
            return Result.success("文章审核成功");
        } else {
            return Result.fail("文章审核失败");
        }
    }

    // 最新文章查看实现

    /**
     * 获取最新文章
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getLatestArticles(Integer pageNum, Integer pageSize) {
        try {
            Page<Article> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.orderByDesc("publish_time");
            IPage<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
            return Result.success("最新文章获取成功", articlePage);
        } catch (Exception e) {
            log.error("获取最新文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 获取最新文章（不带分页）
     * @return
     */
    @Override
    public Result getLatestArticlesWithoutPage() {
        try {
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.orderByDesc("publish_time");
            List<Article> articles = articleMapper.selectList(queryWrapper);
            //输出结果
            log.info("最新文章结果：{}", articles);
            return Result.success("最新文章获取成功", articles);
        } catch (Exception e) {
            log.error("获取最新文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    // 最热标签查看实现

    /**
     * 最热标签查看
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getHotTags(Integer pageNum, Integer pageSize) {
        try {
            Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.groupBy("tag")
                    .select("tag", "count(*) as article_count")
                    .orderByDesc("article_count");
            IPage<Map<String, Object>> tagPage = articleMapper.selectMapsPage(page, queryWrapper);
            return Result.success("最热标签获取成功", tagPage);
        } catch (Exception e) {
            log.error("获取最热标签失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 最热标签查看（不带分页）
     * @return
     */
    @Override
    public Result getHotTagsWithoutPage() {
        try {
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.groupBy("tag")
                    .select("tag", "count(*) as article_count")
                    .orderByDesc("article_count");
            List<Map<String, Object>> tags = articleMapper.selectMaps(queryWrapper);
            return Result.success("最热标签获取成功", tags);
        } catch (Exception e) {
            log.error("获取最热标签失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    // 最热文章查看实现

    /**
     * 最热文章查看
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getHotArticles(Integer pageNum, Integer pageSize) {
        try {
            Page<Article> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.orderByDesc("view_count");
            IPage<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
            return Result.success("最热文章获取成功", articlePage);
        } catch (Exception e) {
            log.error("获取最热文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 最热文章查看（不带分页）
     * @return
     */
    @Override
    public Result getHotArticlesWithoutPage() {
        try {
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.orderByDesc("view_count");
            List<Article> articles = articleMapper.selectList(queryWrapper);
            return Result.success("最热文章获取成功", articles);
        } catch (Exception e) {
            log.error("获取最热文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 文章归档查看实现
     * @param pageNum
     * @param pageSize
     * @return
     */

    // 文章归档类型查看实现
    @Override
    public Result getArticleArchives(Integer pageNum, Integer pageSize) {
        try {
            Page<Map<String, Object>> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.groupBy("archive_type")
                    .select("archive_type", "count(*) as article_count")
                    .orderByDesc("article_count");
            IPage<Map<String, Object>> archivePage = articleMapper.selectMapsPage(page, queryWrapper);
            return Result.success("文章归档类型获取成功", archivePage);
        } catch (Exception e) {
            log.error("获取文章归档类型失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 文章归档类型查看实现（不带分页）
     * @return
     */
    @Override
    public Result getArticleArchivesWithoutPage() {
        try {
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.groupBy("archive_type")
                    .select("archive_type", "count(*) as article_count")
                    .orderByDesc("article_count");
            List<Map<String, Object>> archives = articleMapper.selectMaps(queryWrapper);
            return Result.success("文章归档类型获取成功", archives);
        } catch (Exception e) {
            log.error("获取文章归档类型失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    // 根据标签查看文章实现

    /**
     * 根据标签查看文章实现
     * @param tag
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getArticlesByTag(String tag, Integer pageNum, Integer pageSize) {
        try {
            Page<Article> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.eq("tag", tag);
            IPage<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
            return Result.success("标签文章获取成功", articlePage);
        } catch (Exception e) {
            log.error("获取标签文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 根据标签查看文章实现（不带分页）
     * @param tag
     * @return
     */
    @Override
    public Result getArticlesByTagWithoutPage(String tag) {
        try {
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.eq("tag", tag);
            List<Article> articles = articleMapper.selectList(queryWrapper);
            return Result.success("标签文章获取成功", articles);
        } catch (Exception e) {
            log.error("获取标签文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    // 根据归档类型查看文章实现

    /**
     * 根据归档类型查看文章实现
     * @param archiveType
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Result getArticlesByArchiveType(String archiveType, Integer pageNum, Integer pageSize) {
        try {
            Page<Article> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.eq("archive_type", archiveType);
            IPage<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
            return Result.success("归档类型文章获取成功", articlePage);
        } catch (Exception e) {
            log.error("获取归档类型文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 根据归档类型查看文章实现（不带分页）
     * @param archiveType
     * @return
     */
    @Override
    public Result getArticlesByArchiveTypeWithoutPage(String archiveType) {
        try {
            QueryWrapper<Article> queryWrapper = createBaseQueryWrapper();
            queryWrapper.eq("archive_type", archiveType);
            List<Article> articles = articleMapper.selectList(queryWrapper);
            return Result.success("归档类型文章获取成功", articles);
        } catch (Exception e) {
            log.error("获取归档类型文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 创建基础查询条件（已发布状态）
     */
    private QueryWrapper<Article> createBaseQueryWrapper() {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "已发布");
        return queryWrapper;
    }


    /**
     * 获取所有标签
     * @return
     */
    @Override
    public Result getAllTags() {
        try {
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT tag");
            List<Map<String, Object>> tagMaps = articleMapper.selectMaps(queryWrapper);
            List<String> tags = new ArrayList<>();
            for (Map<String, Object> tagMap : tagMaps) {
                if (tagMap.get("tag") != null) {
                    tags.add(tagMap.get("tag").toString());
                }
            }
            return Result.success("获取所有标签成功", tags);
        } catch (Exception e) {
            log.error("获取所有标签失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 获取时间归档
     * @return
     */
    @Override
    public Result getTimeArchives() {
        try {
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT archive_type");
            List<Map<String, Object>> archiveMaps = articleMapper.selectMaps(queryWrapper);
            List<String> archives = new ArrayList<>();
            for (Map<String, Object> archiveMap : archiveMaps) {
                if (archiveMap.get("archive_type") != null) {
                    archives.add(archiveMap.get("archive_type").toString());
                }
            }
            return Result.success("获取所有时间归档成功", archives);
        } catch (Exception e) {
            log.error("获取所有时间归档失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getArticlesByUserId(Long userId, Integer pageNum, Integer pageSize) {
        try{
            Page<Article> page = new Page<>(pageNum,pageSize);
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            IPage<Article> articleIPage = articleMapper.selectPage(page, queryWrapper);
            return Result.success("获取用户文章成功",articleIPage);
        }catch (Exception e){
            log.error("获取用户文章失败", e);
            return Result.fail("系统错误，请稍后再试");
        }
    }

    /**
     * 获取文章详情
     * @param articleId
     * @return
     */
    @Override
    public Result getArticleDetail(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        if (article != null) {
            return Result.success("获取文章详情成功", article);
        } else {
            return Result.fail("文章不存在");
        }
    }

    /**
     * 增加文章阅读量
     * @param articleId
     * @return
     */
    @Override
    @Transactional
    public Result increaseArticleViewCount(Long articleId) {
        Article article = articleMapper.selectById(articleId);
        if (article != null) {
            article.setViewCount(article.getViewCount() + 1);
            int result = articleMapper.updateById(article);
            if (result > 0) {
                return Result.success("文章阅读量增加成功");
            } else {
                return Result.fail("文章阅读量增加失败");
            }
        } else {
            return Result.fail("文章不存在");
        }
    }

    @Override
    public Result getArticlesByStatus(Long userId, String status) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);

        // 根据状态参数查询对应文章
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }

        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success("获取文章列表成功", articles);
    }
}
